package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
@Slf4j
public class GulimallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException exception){
        BindingResult result = exception.getBindingResult();
        Map<String, String> map = new HashMap<>();
        result.getFieldErrors().forEach((item) -> {
            String message = item.getDefaultMessage();
            String code = item.getField();
            map.put(code, message);
        });
        return R.error(BizCodeEnum.VILID_EXCEPTION.getCode(), BizCodeEnum.VILID_EXCEPTION.getMsg()).put("data", map);
    }

    public R handleException(Throwable throwable){
        return R.error(BizCodeEnum.NUKNOW_EXCEPTION.getCode(), BizCodeEnum.VILID_EXCEPTION.getMsg()).put("data", throwable.getMessage());
    }
}
